<template>
  <div class="user-management">
    <!-- 页面标题区域 -->
    <div class="page-title">
      <div class="title-content">
        <i class="el-icon-user"></i>
        <span>用户管理</span>
      </div>
      <div class="title-right">
        <span class="time">{{ currentTime }}</span>
      </div>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名/账号/邮箱搜索"
        prefix-icon="el-icon-search"
        @input="handleSearch"
        size="small"
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <el-button 
        type="primary" 
        icon="el-icon-plus"
        @click="handleAdd"
        size="small"
      >新增用户</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" align="center"/>
        <el-table-column prop="username" label="用户名" align="center"/>
        <el-table-column prop="account" label="账号" align="center"/>
        <el-table-column prop="email" label="邮箱" align="center"/>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="dark">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template slot-scope="scope">
            <el-tag type="primary" effect="dark">
              {{ scope.row.role === '0' ? '超级管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="success"
              @click="handleAssignRole(scope.row)"
              icon="el-icon-s-check"
            >分配角色</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      custom-class="feedback-dialog"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="userForm.account" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :append-to-body="true"
      custom-class="feedback-dialog"
    >
      <el-transfer
        v-model="selectedRoles"
        :data="formattedRoleList"
        :titles="['可选角色', '已选角色']"
        :props="{
          key: 'id',
          label: 'roleName'
        }"
      ></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'UserManagement',
  data() {
    return {
      loading: false,
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: '',
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: '新增用户',
      userForm: {
        username: '',
        account: '',
        password: '',
        email: '',
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      roleDialogVisible: false,
      roleList: [],
      selectedRoles: [],
      currentUserId: null,
      currentTime: ''
    }
  },
  computed: {
    formattedRoleList() {
      return this.roleList.map(role => ({
        id: role.id,
        roleName: role.roleName,
        key: role.id
      }))
    }
  },
  created() {
    this.fetchData()
    this.updateTime()
    setInterval(this.updateTime, 1000)
  },
  methods: {
    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleString()
    },
    async fetchData() {
      this.loading = true
      try {
        const res = await axios.get('/api/system/user/list', {
          params: {
            current: this.currentPage,
            size: this.pageSize,
            keyword: this.searchKeyword
          }
        })
        this.userList = res.data.data.records
        this.total = res.data.data.total
      } catch (error) {
        console.error(error)
        this.$message.error('获取用户列表失败')
      }
      this.loading = false
    },
    
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    handleAdd() {
      this.dialogType = 'add'
      this.dialogTitle = '新增用户'
      this.userForm = {
        username: '',
        account: '',
        password: '',
        email: '',
        status: 1
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑用户'
      this.userForm = { ...row }
      delete this.userForm.password
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户?', '提示', {
          type: 'warning'
        })
        await axios.delete(`/api/system/user/${row.id}`)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        console.error(error)
      }
    },

    async submitForm() {
      try {
        await this.$refs.userForm.validate()
        if (this.dialogType === 'add') {
          await axios.post('/api/system/user/create', this.userForm)
          this.$message.success('创建成功')
        } else {
          await axios.put(`/api/system/user/${this.userForm.id}`, this.userForm)
          this.$message.success('更新成功')
        }
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        console.error(error)
      }
    },

    async handleAssignRole(row) {
      this.currentUserId = row.id
      this.roleDialogVisible = true
      
      try {
        // 获取所有角色
        const res = await axios.get('/api/system/role/list')
        this.roleList = res.data.data || []
        
        // 获取用户当前角色
        if (row.id) {  // 确保有效的用户ID
          const userRoles = await axios.get(`/api/system/user/${row.id}/role/list`)
          if (userRoles.data.code === 200) {
            this.selectedRoles = (userRoles.data.data || []).map(role => role.roleId)
          } else {
            this.$message.warning('获取用户角色失败')
            this.selectedRoles = []
          }
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
        this.selectedRoles = []
      }
    },

    async submitRoles() {
      try {
        const selectedRoleData = this.roleList.filter(role => 
          this.selectedRoles.includes(role.id)
        )
        
        await axios.post(`/api/system/user/${this.currentUserId}/roles`, {
          roleIds: this.selectedRoles,
          roleNames: selectedRoleData.map(role => role.roleName)
        })
        
        this.$message.success('角色分配成功')
        this.roleDialogVisible = false
        this.fetchData()
      } catch (error) {
        console.error('分配角色失败:', error)
        this.$message.error('分配角色失败')
      }
    }
  }
}
</script>

<style>
/* 注意：这里不使用 scoped，以便样式能够作用到弹窗 */
.feedback-dialog {
  background: #fff !important;
}

.feedback-dialog .el-dialog__header {
  background: #1a237e;
  padding: 20px;
  border-radius: 8px 8px 0 0;
  margin-right: 0;
}

.feedback-dialog .el-dialog__title {
  color: white;
  font-size: 18px;
  line-height: 24px;
}

.feedback-dialog .el-dialog__headerbtn {
  top: 15px;
}

.feedback-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.feedback-dialog .el-dialog__body {
  padding: 30px 20px;
  background: #fff;
}

.feedback-dialog .el-dialog__footer {
  padding: 15px 20px;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

/* 遮罩层样式 */
.v-modal {
  opacity: 0.5 !important;
}
</style>

<style scoped>
.user-management {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 16px;
}

.page-title {
  background: #1a237e;
  color: white;
  padding: 16px 24px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.title-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
}

.title-content i {
  font-size: 24px;
}

.title-right {
  font-size: 14px;
  opacity: 0.8;
}

.search-bar {
  background: white;
  padding: 16px;
  border-radius: 8px;
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-bar .el-input {
  width: 300px;
}

.table-container {
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 自定义表格样式 */
.el-table {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #1a237e !important;
  color: white !important;
  font-weight: 500;
  padding: 12px 0;
}

.el-table td {
  padding: 12px 0;
}

/* 分页器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding-top: 16px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
}

/* 按钮样式 */
.el-button--mini {
  border-radius: 4px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }
  
  .search-bar .el-input {
    width: 100%;
  }
}

/* 角色选择器样式 */
.el-transfer {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

/* 按钮样式优化 */
.el-button--primary {
  background-color: #1a237e;
  border-color: #1a237e;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #283593;
  border-color: #283593;
}
</style>